import mongoose from "mongoose";
import bcrypt from "bcryptjs";

const userSchema = mongoose.Schema(
  {
    // 用户名
    name: {
      type: String,
      required: true,
    },
    // 邮箱
    email: {
      type: String,
      required: true,
      unique: true,
    },
    // 密码
    password: {
      type: String,
      required: true,
    },
    // 是否管理员
    isAdmin: {
      type: Boolean,
      required: true,
      default: false,
    },
  },
  {
    // 时间戳
    timestamps: true,
  }
);

//用户注册，对密码进行加密保存
userSchema.pre("save", async function (next) {
  //判断password是否被修改
  if (!this.isModified("password")) {
    next();
  }
  //对密码进行加密
  const salt = await bcrypt.genSalt(10);
  this.password = await bcrypt.hash(this.password, salt);
});

//将前端返回的密码，跟数据表中已经加密的密码进行解密比对
userSchema.methods.matchPassword = async function (enterPassword) {
  return await bcrypt.compare(enterPassword, this.password);
};

const User = mongoose.model("User", userSchema);

export default User;
